package pl.vanta.mjuzik2.impl.files;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import pl.vanta.mjuzik2.api.AudioFile;
import pl.vanta.mjuzik2.api.FileInfo;
import pl.vanta.mjuzik2.api.services.FilesService;
import pl.vanta.mjuzik2.api.services.FormatService;
import pl.vanta.mjuzik2.api.services.PlaylistService;
import pl.vanta.utils.commons.FileUtils;

import com.google.inject.Inject;

public class FilesServiceImpl implements FilesService
{
	private final PlaylistService	playlistService;
	private final FormatService		formatService;
	private Set<AudioFile>			files;

	@Inject
	public FilesServiceImpl(PlaylistService playlistService, FormatService formatService)
	{
		this.playlistService = playlistService;
		this.formatService = formatService;

		this.files = new HashSet<AudioFile>();
	}

	@Override
	public Collection<AudioFile> getFiles()
	{
		return Collections.unmodifiableCollection(this.files);
	}

	@Override
	public void loadFiles(Collection<File> locations)
	{
		for (File file : locations)
		{

		}
	}

	@Override
	public void unloadAllFiles()
	{
		this.files.clear();
	}

	private AudioFile convert(File file, boolean checkFilePresenceOnLoad, boolean lazyPlaylistLoading)
	{
		AudioFile af = new AudioFile(file);

		if (!checkFilePresenceOnLoad)
		{
			if (!file.isFile() || !file.exists())
			{
				return null;
			}
		}

		if (!lazyPlaylistLoading)
		{
			FileInfo fi = this.formatService.getFileInfo(file);

			if (fi == null)
			{
				return null;
			}

			af.setFileInfo(fi);
		}

		af.setHash(createFileHash(file));

		return af;
	}

	private List<AudioFile> convert(List<File> files, boolean checkFilePresenceOnLoad, boolean lazyPlaylistLoading)
	{
		List<AudioFile> audioFiles = new ArrayList<AudioFile>();

		for (File file : files)
		{
			AudioFile af = convert(file, checkFilePresenceOnLoad, lazyPlaylistLoading);

			if (af != null)
			{
				audioFiles.add(af);
			}
		}

		return audioFiles;
	}

	private String createFileHash(File file)
	{
		String hash = String.valueOf(file.length());

		return hash;
	}

	private List<File> getAllFiles(List<File> files)
	{
		return FileUtils.getAllFilesRecursive(files, this.formatService.getMusicFilesFilter());
	}

	private List<File> getAllFilesFromPlaylists(File[] files)
	{
		List<File> fileList = new ArrayList<File>();

		List<File> playlists = FileUtils.getAllFilesRecursive(files, this.playlistService.getPlaylistFilesFilter());

		for (File file : playlists)
		{
			fileList.addAll(this.playlistService.loadPlaylist(file));
		}

		return fileList;
	}
}